package modules.communication
{
	import flash.net.NetConnection;
	import flash.net.Responder;

	import modules.GameDispatcher;
	import modules.GameEvent;
	import modules.login.Login;

	public class MsgSender
	{
		protected function onGameEvent(event:GameEvent):void
		{
			switch (event.type)
			{
				case CommunicationEvent.LOGIN_REQ:
					netConnection.call("loginReq", new Responder(function(info:*):void
					{
						logger(info);

						Login.logined = info.loginSucceed;
						if (info.userinfo)
						{
							GlobalData.userInfo.username = info.userinfo.username;

						}

						dispatcher.dispatchEvent(new CommunicationEvent(CommunicationEvent.LOGIN_ACK, info));
					}, function(status:*):void
					{
						logger(status);
					}), event.data);
					break;
				case CommunicationEvent.LOGOUT_REQ:
					netConnection.call("logoutReq", new Responder(function(info:*):void
					{
						logger(info);

						Login.logined = info.logoutSucceed;
						if (info.logoutSucceed)
							dispatcher.dispatchEvent(new CommunicationEvent(CommunicationEvent.LOGOUT_ACK, info));
						
					}, function(status:*):void
					{
						logger(status);
					}));
					break;
				case CommunicationEvent.CREATEROOM_REQ:
					netConnection.call("createRoomReq", new Responder(function(info:*):void
					{
						logger(info);


					}, function(status:*):void
					{
						logger(status);
					}));
					break;
			}
		}

		/****************************************************/
		private var netConnection:NetConnection;

		public static var dispatcher:GameDispatcher = GameDispatcher.instance;

		public function MsgSender(netConnection:NetConnection)
		{
			this.netConnection = netConnection;

			addListeners();
		}

		private function addListeners():void
		{
			dispatcher.addEventListener(CommunicationEvent.LOGIN_REQ, onGameEvent);
			dispatcher.addEventListener(CommunicationEvent.LOGOUT_REQ, onGameEvent);
			dispatcher.addEventListener(CommunicationEvent.CREATEROOM_REQ, onGameEvent);

		}
	}
}
